<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import vkDataInputNumberBox from '@/components/vk-data-input-number-box.vue'
import type { IcartItem } from '@/types/cart'
import { ref, computed } from 'vue'
import { useCart, useOrder } from '@/stores'
import { formatChineseJson } from '@/utils/http'
const { addOrderData } = useOrder()
const {
  clearAll,
  getCartTotalNum,
  getCartData,
  checkedHandler,
  deleteById,
  getSelectedList,
  onSelectedAll,
} = useCart()

const numChange = (e: any, record: any) => {
  record.num = e.value
  setCartTabBarBadge()
}

const setCartTabBarBadge = () => {
  const totalNum = getCartTotalNum()
  if (totalNum > 0) {
    uni
      .setTabBarBadge({
        index: 2,
        text: totalNum.toString(),
      })
      .catch((err) => {
        console.error('cart:', err)
      })
  } else {
    uni.removeTabBarBadge({
      index: 2,
    })
  }
}

// 点击删除按钮
const onDeleteCart = (id: string | number) => {
  // 弹窗二次确认
  uni.showModal({
    content: '是否删除',
    success: async (res) => {
      if (res.confirm) {
        deleteById(id)
        setCartTabBarBadge()
        // cartList.value = cartList.value.filter((item) => {
        //   return item.id !== id
        // })
        // 后端删除单品
        // await deleteMemberCartAPI({ ids: [skuId] })
        // 重新获取列表
        // getMemberCartData()
      }
    },
  })
}
// 修改选中状态-单品修改
const onChangeSelected = (item: IcartItem) => {
  checkedHandler(item)
  setCartTabBarBadge()
  // 后端数据更新
  // putMemberCartBySkuIdAPI(item.skuId, { checked: item.checked })
}

// 计算全选状态
const isSelectedAll = computed(() => {
  return getCartData().length > 0 && getCartData().every((item) => item.checked)
})

// 修改选中状态-全选修改
const onChangeSelectedAll = () => {
  onSelectedAll(!isSelectedAll.value)
  setCartTabBarBadge()
  // 后端数据更新
  // putMemberCartSelectedAPI({ checked: _isSelectedAll })
}

// 计算选中总件数
const selectedCartListCount = computed(() => {
  return getCartData()
    .filter((item) => item.checked)
    .reduce((sum, item) => sum + (item.num || 0), 0)
})

// 计算选中总金额
const selectedCartListMoney = computed(() => {
  return getCartData()
    .filter((item) => item.checked)
    .reduce((sum, item) => sum + (item.num || 0) * item.price, 0)
    .toFixed(2)
})

// 结算按钮
const gotoPayment = () => {
  const res = getSelectedList()
  if (res.length === 0) {
    return uni.showToast({
      icon: 'none',
      title: '请选择商品',
    })
  }
  addOrderData(res)
  uni.navigateTo({ url: '/pagesOrder/create/create' })
}

const clearCart = () => {
  clearAll()
  setCartTabBarBadge()
}

// 初始化调用: 页面显示触发
onShow(() => {
  setCartTabBarBadge()
})

const getSetmealId = (id: string) => {
  return id.split('_')[0]
}
</script>

<template>
  <scroll-view scroll-y class="scroll-view">
    <template>
      <view class="cart-list" v-if="getCartData().length > 0">
        <view class="cart-clear">
          <text class="all" :class="{ checked: isSelectedAll }" @click="onChangeSelectedAll"
            >全选</text
          >
          <view class="btn" @click="clearCart()"
            ><text class="iconfont icon-RectangleCopy8"></text> <text>清空</text></view
          >
        </view>
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <uni-swipe-action-item
            v-for="record in getCartData()"
            :key="record.id"
            class="cart-swipe"
          >
            <!-- 商品信息 -->
            <view class="goods">
              <text
                class="checkbox"
                :class="{ checked: record.checked }"
                @tap="onChangeSelected(record)"
              ></text>
              <navigator
                :url="
                  record.isSetmeal
                    ? `/pages/goods/setmealGoods?id=${record.goods_id}`
                    : `/pages/goods/goods?id=${record.hasSku ? record.goods_id : record.id}`
                "
                hover-class="none"
                class="navigator"
              >
                <image mode="aspectFill" class="picture" :src="record.image"></image>
                <view class="meta">
                  <view class="name ellipsis">{{ record.name }}</view>
                  <rich-text class="attrsText ellipsis" :nodes="record.description"></rich-text>
                  <rich-text
                    class="attrsText ellipsis"
                    v-if="record.specification"
                    :nodes="formatChineseJson(record.specification)"
                  ></rich-text>
                  <view class="price">{{ record.price }}</view>
                </view>
              </navigator>
              <!-- 商品数量 -->
              <view class="count">
                <vk-data-input-number-box
                  v-model="record.num"
                  :min="0"
                  :max="50"
                  :step="1"
                  :step-strictly="true"
                  :disabled="false"
                  :disabled-input="false"
                  :cursor-spacing="100"
                  :long-press="true"
                  :press-time="250"
                  :positive-integer="true"
                  @change="(e) => numChange(e, record)"
                ></vk-data-input-number-box>
              </view>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <button class="button delete-button" @tap="onDeleteCart(record.id)">删除</button>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <!-- 购物车空状态 -->
      <view class="cart-blank" v-else>
        <image src="/static/images/blank_cart.png" class="image" />
        <text class="text">购物车还是空的，快来挑选吧</text>
        <navigator open-type="switchTab" url="/pages/index/index" hover-class="none">
          <button class="button">去首页看看</button>
        </navigator>
      </view>
      <view class="toolbar">
        <view class="tip"
          ><text class="text">合计：</text>
          <text class="amount">{{ selectedCartListMoney }}</text>
        </view>
        <view class="button-grounp">
          <view class="button payment-button" :class="{ disabled: false }" @tap="gotoPayment()">
            <text class="text">去结算({{ selectedCartListCount }})</text>
          </view>
        </view>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <!-- <view class="login-blank" v-else>
      <text class="text">登录后可查看购物车中的商品</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view> -->
  </scroll-view>
</template>

<style lang="scss">
@use 'sass:math';
@import '@/styles/variables.scss';
$rpx-size: 1rpx; // 基准rpx大小，可根据需要调整或直接使用具体数值
$height: 120;
$height-size: $height * $rpx-size;
$border-radius-size: (math.div($height, 2)) * $rpx-size;
$toolbar-bottom-height: ($height + 20) * $rpx-size;

$check-color: $color;

// 滚动容器
.scroll-view {
  flex: 1;
}

// 购物车列表
.cart-list {
  padding: 0 20rpx;
  // background-color: $background-color;
  padding-bottom: $toolbar-bottom-height;
  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 20rpx 20rpx 80rpx;
    border-radius: 10rpx;
    background-color: #fff;
    position: relative;
    border: 1px solid $border-color;
    border-radius: $border-small-radius;
    overflow: hidden;

    .navigator {
      display: flex;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 0;

      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 100%;

      &::before {
        content: '\e6f4';
        font-family: 'iconfont' !important;
        font-size: 66rpx;
        color: $color;
        margin-right: 8rpx;
        margin-left: -10rpx;
      }

      &.checked::before {
        content: '\e6be';
        font-family: 'iconfont' !important;
        font-size: 66rpx;
        margin-right: 8rpx;
        margin-left: -10rpx;
        color: $check-color;
      }
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
      border-radius: $border-small-radius;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      max-height: 74rpx;
      font-size: $font-medium-size;
      color: $good-font-title-color;
      font-weight: $font-medium-weight;
    }

    .attrsText {
      font-size: $font-size;
      align-self: flex-start;
      border-radius: 4rpx;
      color: $good-font-con-color;
      background-color: #fff;
    }

    .price {
      line-height: 1;
      font-size: $font-size;
      margin-bottom: 2rpx;
      color: $price-font-color;

      &::before {
        content: '￥';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 20rpx;
      right: 24rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 180rpx;
      height: 48rpx;

      // .minus,
      // .plus {
      //   font-size: 32rpx;
      //   color: #fff;
      //   height: 46rpx;
      //   width: 46rpx;
      //   border-radius: 50%;
      //   text-align: center;
      //   line-height: 1.4;
      //   background-color: #2f993e;
      //   font-weight: bold;
      //   border: 1px solid #2f993e;
      // }
      // .minus {
      //   color: #2f993e;
      //   background-color: #fff;
      // }

      // .input {
      //   flex: 1;
      //   text-align: center;
      //   font-size: 24rpx;
      //   color: #444;
      // }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: $red-color;
      margin-left: 10rpx;
      border-radius: $border-small-radius;
      width: 100rpx;
    }
  }
}

// 空状态
.cart-blank,
.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 60vh;
  .image {
    width: 400rpx;
    height: 281rpx;
  }
  .text {
    color: #444;
    font-size: 26rpx;
    margin: 20rpx 0;
  }
  .button {
    width: 240rpx !important;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: #27ba9b;
  }
}

// 吸底工具栏
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: var(--window-bottom);
  z-index: 9;

  height: $height-size;
  border-radius: $border-radius-size;
  border: 1px solid $border-color;
  margin: 0 20rpx 20rpx 20rpx;
  display: flex;
  align-items: center;
  box-sizing: content-box;
  overflow: hidden;

  .tip {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    height: 100%;
    padding-right: 20rpx;
    background-color: #fff;
    flex: 1;
    .text {
      margin-left: 45rpx;
      font-size: $font-medium-size;
      color: #000;
      font-weight: $font-medium-weight;
    }
    .amount {
      font-size: 20px;
      color: $price-font-color;
      &::before {
        content: '￥';
        font-size: 12px;
      }
    }
  }
  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: $height-size;
    font-size: 13px;
    color: #fff;
    background: $check-color;
    width: 240rpx;
    border-radius: 0 $border-radius-size $border-radius-size 0;

    .button {
      width: 100%;
      border-radius: 0 $border-radius-size $border-radius-size 0;
    }

    .payment-button {
      background-color: $check-color;

      &.disabled {
        .text {
          color: #ccc;
        }
      }
    }
  }
}
.cart-clear {
  display: flex;
  justify-content: space-between;
  padding: 0 10rpx;
  align-items: center;
  border: 1px solid $border-color;
  border-radius: $border-small-radius;
  font-size: $font-size;
  height: 100rpx;
  background-color: #fff;
  .all {
    color: #000;
    font-weight: $font-medium-weight;
    font-weight: $font-regular-weight;
    display: flex;
    align-items: center;
    font-size: $font-medium-size;
    &::before {
      content: '\e65d';
      font-family: 'iconfont' !important;
      font-size: 50rpx;
      color: $color;
      margin-right: 8rpx;
      margin-left: -10rpx;
    }
    &.checked {
      &::before {
        content: '\e77d';
        font-family: 'iconfont' !important;
        font-size: 50rpx;
        color: $color;
        margin-right: 8rpx;
        margin-left: -10rpx;
      }
    }
  }
  .btn {
    color: $color;
    display: flex;
    flex-direction: row;
    align-items: center;

    .iconfont {
      font-weight: $font-medium-weight;
    }
  }
}
</style>
